package com.glodon.paas.job.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

import com.glodon.paas.job.model.AgentStatus;
import com.glodon.paas.job.model.GlobalStatus;
import com.glodon.paas.job.model.MonitorStatus;
import com.glodon.paas.job.model.Task;

public class TestUtil {

    public static SessionFactory createSessionFactory() {
        try {
            String driverClassName = "com.mysql.jdbc.Driver";
            String username = "root";
            String password = "";
            createDatabase(driverClassName, username, password);
            AnnotationSessionFactoryBean factory = new AnnotationSessionFactoryBean();
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl("jdbc:mysql://localhost/paas_job");
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            factory.setDataSource(dataSource);
            factory.setAnnotatedClasses(new Class[] { Task.class, AgentStatus.class, MonitorStatus.class,
                    GlobalStatus.class });
            Properties props = new Properties();
            props.setProperty("hibernate.hbm2ddl.auto", "create");
            props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
            factory.setHibernateProperties(props);
            factory.afterPropertiesSet();
            SessionFactory sessionFactory = factory.getObject();
            return sessionFactory;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void createDatabase(String driverClassName, String username, String password)
            throws ClassNotFoundException, SQLException {
        Class.forName(driverClassName);
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/paas_job", username, password);
            conn.close();
        } catch (Exception e) {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost", username, password);
            Statement st = conn.createStatement();
            st.execute("CREATE DATABASE paas_job DEFAULT CHARACTER SET utf8");
            st.close();
            conn.close();
        }
    }

}
